#!/usr/bin/python
#
# perfPidStatParser.py - Script for parsing the pidstat output and producing data files on per pid/command arg basis
#

'''
   Created on Jul 30, 2011
   
   @author: Krystian Brachmanski
'''

import os
import sys
import getopt
import logging
import directoryHandler
import latexUtils
import ConfigParser
import yapcgMain

#Global variables
configFile = './config/perfAnalyzer.cfg'
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
log = logging.getLogger('yapcg.perfparser.main')
'''
Logger to be used for the MainApp
'''
#cpuThresholdList = []
#memThresholdList = []
#cpuThreshold = None
#memThreshold = None
texGenerator = None
'''
Generator of tex file to be included in the main doc
'''
dirHandler = None
'''
Directory structure handler
'''

def usage():
    '''
    Print the usage/help information
    '''
    print "Usage : " + sys.argv[0] + " [-h] [-c <config_filename>] [-v]"
    print ""
    print "where:"
    print "  -h     - prints this help screen"
    print "  -c     - configuration file name"
    print "  -v     - verbose mode (logging level set to DEBUG)"
    print "" 
    print "@2011 Copyright: YAPCG development team"
    return

def checkFileExist(inputFile,filetype):
    if inputFile == "" :
        log.info(filetype + " file name not defined... Skipping...")
        return False

    if os.path.isfile(inputFile) != True :
        log.error("Provided file : " + inputFile + " does not exists or is not a file...")
        return False

    return True

def parseSarCpuFile(sarGen):
    '''
    Parse the sar cpu file
    '''
    inSarCpuFile = c.get('config','cpuFile')
    if checkFileExist(inSarCpuFile,"sarcpu") != True :
	return False
    sarGen.parseSarCpuFile(inSarCpuFile)	
    return True

def parseSarMemFile(sarGen):
    '''
    Parse the sar mem file
    '''
    inSarMemFile = c.get('config','memFile')
    if checkFileExist(inSarMemFile,"sarmem") != True :
        return False
    sarGen.parseSarMemFile(inSarMemFile)
    return True

def parseSarFile():
    '''
    Parse the sar file
    '''
    sarGen = yapcgMain.yapcgSarGenerator(dirHandler)
    cpu = parseSarCpuFile(sarGen)
    mem = parseSarMemFile(sarGen)
    
    texGenerator.generalCpuStatistics = sarGen.stats
    if cpu == True :
	texGenerator.generalCpuSectionFigures = sarGen.sarCpuList
    if mem == True :
        texGenerator.generalMemSectionFigures = sarGen.sarMemList


def parsePidstatFile():
    '''
    Parse the pidstat file
    '''
    
    bootchartFile = c.get('config','bootchartFile')
    inputFile = c.get('config','pidstatFile')

    if checkFileExist(inputFile,"pidstat") != True :
	return False

    procNum = c.get('filtering','numberOfPocessesOnLegend')
    #cpuThreshold = c.get('filtering','cpuThreshold')
    #memThreshold = c.get('filtering','memThreshold')
    processBlackList = c.get('filtering','processBlacklist')

    yapcgPidstat = yapcgMain.yapcgPidstatGenerator(dirHandler)
    yapcgPidstat.parsePidstatFile(inputFile, procNum, processBlackList)

    texGenerator.generalSectionFigures = yapcgPidstat.generalSectionFigure
    texGenerator.processCpuDetailFigures = yapcgPidstat.detailCpuSectionFigure
    texGenerator.processMemDetailFigures = yapcgPidstat.detailMemSectionFigure
    texGenerator.processIoDetailFigures = yapcgPidstat.detailIoSectionFigure
    
    texGenerator.addBootchartSectionFigure(bootchartFile)
    texGenerator.addIgnoredExecutionStatistics(yapcgPidstat.pidParser.getBlacklistStatistics())
    texGenerator.addIgnoredMaxCpuStatistics(yapcgPidstat.pidParser.getBlacklistCpuStatistics())
    texGenerator.addIgnoredMaxMemStatistics(yapcgPidstat.pidParser.getBlacklistMemStatistics())
    
def main():
    '''
    Main method
    '''
    global c, configFile, dirHandler, texGenerator
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:c:v", ["help", "config=", "verbose"]) 
        for opt, arg in opts:                
            if opt in ("-h", "--help"): 
                usage()                     
                sys.exit()                  
            elif opt in ("-c", "--config"): 
                configFile = arg
            elif opt in ("-v", "--verbose"):
                log.setLevel(logging.DEBUG)
                log.debug("Running program in verbose mode")
  
    except getopt.GetoptError:           
        usage()                          
        sys.exit(2)   

    log.info("Reading configuration from file : " + configFile)
    c = ConfigParser.ConfigParser()
    c.read(configFile)

    texFile = c.get('config','texOutputFile')

    # Variables to control the production fo gnuplot config files
    texGenerator = latexUtils.TexReportGenerator()

    dirHandler = directoryHandler.DirectoryHandler(c)

    log.info("Checking directory structure...")
    dirHandler.verifyDirectoryStricture()

    parseSarFile()
    parsePidstatFile()

    log.info("Generating tex doc to file : " + texFile)
    texGenerator.writeTexDocToFile(dirHandler.reportDir + texFile)

    outFormat = c.get('config','outputFormat')
    if outFormat == 'pdf': 
        latexPdfGenerator = latexUtils.PdfLatexGenerator()
        latexPdfGenerator.generatePdf(dirHandler.documentFile, dirHandler.reportDir)
    else:
	latexHtmlGenerator = latexUtils.HtmlLatexGenerator()
	latexHtmlGenerator.generateHtml(dirHandler.documentFile, dirHandler.reportDir)

if __name__ == "__main__":
    main()
